package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.UserDao;
import net.sf.json.JSONObject;
import dao.AdminDao;
import dao.SoftDao;
import dbutil.DBHelper;

public class SwitchStatusServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -78951526015916663L;

	public SwitchStatusServlet() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();

		String table = request.getParameter("table");
		String status = request.getParameter("status");
		String name = request.getParameter("name");

		JSONObject jsonObject = new JSONObject();
		boolean isSuccess = false;
		Connection conn = null;
		SoftDao softDao = null;
		AdminDao adminDao = null;
		UserDao userDao = null;

		try {
			conn = DBHelper.getConnection();
			conn.setAutoCommit(false);
			
			if(table.equals("softwares")) {
				softDao = new SoftDao();
				isSuccess = softDao.editSoftStatus(status, name);
			} else if(table.equals("admins")) {
				adminDao = new AdminDao();
				isSuccess = adminDao.editAdminStatus(status, name);
			} else if(table.equals("users")) {
				userDao = new UserDao();
				isSuccess = userDao.editUserStatus(status, name);
			}

			if(isSuccess) {
				jsonObject.put("retCode", "1");
			} else {
				jsonObject.put("retCode", "0");
				jsonObject.put("desc", "SwitchStatusServlet Dao");
			}

			conn.setAutoCommit(true);
		} catch (SQLException e) {
			e.printStackTrace();
			jsonObject.put("retCode", "0");
			jsonObject.put("desc", "SwitchStatusServlet Exception");
		} finally {
			out.print(jsonObject.toString());
			out.close();
		}

	}

	public void init() throws ServletException {
	}

}
